package com.sakiko.audiobook.search.service.impl;

import com.sakiko.audiobook.album.AlbumInfoFeignClient;
import com.sakiko.audiobook.album.CategoryFeignClient;
import com.sakiko.audiobook.common.constant.RedisConstant;
import com.sakiko.audiobook.common.execption.SakiException;
import com.sakiko.audiobook.common.result.Result;
import com.sakiko.audiobook.model.album.AlbumInfo;
import com.sakiko.audiobook.model.album.BaseCategoryView;
import com.sakiko.audiobook.search.service.ItemService;
import com.sakiko.audiobook.user.client.UserInfoFeignClient;
import com.sakiko.audiobook.vo.album.AlbumStatVo;
import com.sakiko.audiobook.vo.user.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class ItemServiceImpl implements ItemService {

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private CategoryFeignClient categoryFeignClient;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public Map<String, Object> getAlbumInfoById(Long albumId) {
        // 创建返回 map集合对象
        Map<String, Object> map = new HashMap<>();
        // 第三步: 判断布隆过滤器中是否存在对应数据
        // 添加了布隆过滤器，先判断布隆过滤器中是否存在对应专辑信息 ==> 不存在，一定没有！ 存在，可能没有
//        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER);
//        if (!bloomFilter.contains(albumId)) {
//            throw new SakiException(809, "ItemServiceImpl.getAlbumInfoById 专辑不存在！");
//        }
        // 根据专辑 id获取专辑对象
        CompletableFuture<AlbumInfo> albumInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            // 远程调用获取专辑信息数据
            Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfo(albumId);
            Assert.notNull(albumInfoResult, "专辑信息结果集不存在！");
            AlbumInfo albumInfo = albumInfoResult.getData();
            Assert.notNull(albumInfo, "专辑对象不存在！");
            map.put("albumInfo", albumInfo);
            return albumInfo; // 提供后续 thenSupplyAsync操作对象
        }, threadPoolExecutor).exceptionally(throwable -> {
            throwable.getStackTrace();
            return null;
        });
        // 获取分类信息
        CompletableFuture<Boolean> categoryCompletableFuture = albumInfoCompletableFuture.thenApplyAsync(albumInfo -> {
            // 远程调用获取视图信息
            Result<BaseCategoryView> baseCategoryViewResult = categoryFeignClient.getBaseCategoryViewByCategoryId(albumInfo.getCategory3Id());
            Assert.notNull(baseCategoryViewResult, "分类信息结果集不存在！");
            BaseCategoryView baseCategoryView = baseCategoryViewResult.getData();
            Assert.notNull(baseCategoryView, "分类对象不存在！");
            map.put("baseCategoryView", baseCategoryView);
            return true;
        }, threadPoolExecutor).exceptionally(throwable -> {
            throwable.getStackTrace();
            return false;
        });
        // 获取用户对象
        CompletableFuture<Boolean> userCompletableFuture = albumInfoCompletableFuture.thenApplyAsync(albumInfo -> {
            // 远程调用获取作者信息
            Result<UserInfoVo> userInfoResult = userInfoFeignClient.getUserInfo(albumInfo.getUserId());
            Assert.notNull(userInfoResult, "作者信息结果集不存在！");
            UserInfoVo userInfoVo = userInfoResult.getData();
            Assert.notNull(userInfoVo, "作者信息不存在！");
            map.put("announcer", userInfoVo);
            return true;
        }, threadPoolExecutor).exceptionally(throwable -> {
            throwable.getStackTrace();
            return false;
        });
        // 获取专辑统计信息
        CompletableFuture<Boolean> statCompletableFuture = albumInfoCompletableFuture.thenApplyAsync(albumInfo -> {
            // 远程调用获取专辑统计信息
            Result<AlbumStatVo> albumStatVoResult = albumInfoFeignClient.getAlbumStatVo(albumId);
            Assert.notNull(albumStatVoResult, "专辑统计信息结果集不存在！");
            AlbumStatVo albumStatVo = albumStatVoResult.getData();
            Assert.notNull(albumStatVo, "统计信息对象不存在！");
            map.put("albumStatVo", albumStatVo);
            return true;
        }, threadPoolExecutor).exceptionally(throwable -> {
            throwable.getStackTrace();
            return false;
        });
        // 判断异步执行结果
        try {
            if (null == albumInfoCompletableFuture.get() || !categoryCompletableFuture.get() || !userCompletableFuture.get() || !statCompletableFuture.get()) {
                throw new SakiException(809, "ItemServiceImpl.getAlbumInfoById 异步调用失败");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        // 多任务组合
        CompletableFuture.allOf(
                albumInfoCompletableFuture,
                categoryCompletableFuture,
                userCompletableFuture,
                statCompletableFuture
        ).join();
        // 返回数据
        return map;
    }
}
